<template>
  <div ref="jsonEditorContainer" class="jsoneditor-container"></div>
</template>

<script>
import { defineComponent, ref, onMounted, watch } from 'vue'
import JSONEditor from 'jsoneditor'
import 'jsoneditor/dist/jsoneditor.css'

export default defineComponent({
  props: {
    value: {
      type: Object,
      default: () => ({})
    }
  },
  setup(props, { emit }) {
    const jsonEditorContainer = ref(null)
    let editor = null

    onMounted(() => {
      editor = new JSONEditor(jsonEditorContainer.value, {
        mode: 'code',
        onChangeText: (jsonString) => {
          try {
            const json = JSON.parse(jsonString)
            emit('update:value', json)
          } catch (e) {
            console.error('Invalid JSON:', e)
          }
        }
      })
      editor.set(props.value)
    })

    watch(props.value, (newValue) => {
      if (editor) {
        editor.update(newValue)
      }
    })

    return {
      jsonEditorContainer
    }
  }
})
</script>

<style scoped>
.jsoneditor-container {
  height: 400px;
}
</style>
